from django.contrib.auth.models import User
from django_redis import get_redis_connection
from rest_framework import serializers

from apps.oauth.utils import decode_sign_openid


class OAuthQQuserSerializer(serializers.Serializer):
    mobile = serializers.RegexField(label="手机",regex=r'^1[3-9]\d{9}$)')
    sms_code = serializers.CharField(min_length=6,max_length=6,label="短信")
    access_token = serializers.CharField(label="加密openid")
    password = serializers.CharField(min_length=8, max_length=20, label="密码")
    #1.多字段校验
    def validate(self,attrs):
        #1,校验openid
        openid = decode_sign_openid(attrs["access_token"])
        if not openid:
            raise serializers.ValidationError("openid错误")

        #2.校验短信验证码
        mobile  = attrs["mobile"]
        sms_code = attrs["sms_code"]

        redis_conn = get_redis_connection("code")
        redis_sms_code  = redis_conn.get("sms_code_%s"%mobile)
        if  not redis_sms_code:
            raise serializers.ValidationError("短信验证码过期")

        if sms_code != redis_sms_code.decode():
            raise  serializers.ValidationError("短信验证码错误")

        #3.校验密码
        user = None
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            #判断密码是否正确
            if not user.check_password(attrs["password"]):
                raise serializers.ValidationError("密码错误")

        #4.返回响应,添加user和openid
        attrs["openid"] = openid
        attrs["user"] = user
        return  attrs

    #2.重写creat方法入库数据
    def create(self,validate_data):
        """

        :param validate_data: 就是上面校验后的数据
        :return:
        """
        #1,获取数据
        openid = validate_data["openid"]
        user = validate_data["user"]


        # 2.判断是否存在user
        if not user:
            user  = User.objects.create(
                username= validate_data['username'],
                password  = validate_data['password'],
                mobile = validate_data['mobile']
            )

        #3.创建OAuthQQUser对象,绑定美多用户
        OAuthQQUser.objescts.create(openid=openid,user=user)

        #4.返回
        return user




